//
//  DateSelectionViewController.m
//  WorkManager
//
//  Created by iD Student on 7/17/12.
//  Copyright (c) 2012 iD Student. All rights reserved.
//

#import "DateSelectionViewController.h"

@implementation DateSelectionViewController
@synthesize appReport;
@synthesize datePicker;
@synthesize dateLabel;
@synthesize timeLabel;
@synthesize dateCell;
@synthesize timeCell;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)updateDateText
{    
    //Create the calendar in which to place the date
    NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    
    //Create the time components to store the components of now
    NSDateComponents *dateComponents = [gregorian components:(NSMonthCalendarUnit | NSDayCalendarUnit | NSYearCalendarUnit| NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:[datePicker date]];
    
    //Create a string for the date
    NSString *dateString = [NSString stringWithFormat:@"%d/%d/%d", [dateComponents month] , [dateComponents day], [dateComponents year]];
    [dateLabel setText:dateString];
    
    //Create a string for the time
    //Bring the hour under twelve if necessary
    NSString *amPmString;
    if([dateComponents hour]>12)
    {
        [dateComponents setHour:([dateComponents hour]-12)];
        amPmString = @"PM";
    }
    else {
        amPmString = @"AM";
    }
    
    NSString *timeString;
    if([dateComponents minute]<10)
        timeString = [NSString stringWithFormat:@"%d:0%d %@", [dateComponents hour] , [dateComponents minute] , amPmString];
    else
        timeString = [NSString stringWithFormat:@"%d:%d %@", [dateComponents hour] , [dateComponents minute] , amPmString];
    
    [timeLabel setText:timeString];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [datePicker setDate:[appReport date]];
    [self updateDateText];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [appReport setDate:[datePicker date]];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [datePicker release];
    [dateLabel release];
    [timeLabel release];
    [dateCell release];
    [timeCell release];
    [super dealloc];
}

- (IBAction)datePickerValueChanged:(id)sender {
    [self updateDateText];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([indexPath row]==0)
    {
        [timeCell setSelected:NO];
        [datePicker setDatePickerMode:UIDatePickerModeTime];
    }
    else
    {
        [dateCell setSelected:NO];
        [datePicker setDatePickerMode:UIDatePickerModeDate];
        
    }
}
@end
